<!DOCTYPE html>
<html>
<head>
<!--    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">-->
    <title>Chat</title>
    <script src="/marked.min.js"></script>
    <script src="/echarts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            height: 100vh;
        }

        #chatbox {
            flex-grow: 1;
            border: 1px solid #ccc;
            overflow-y: auto;
            margin: 20px;
            padding: 10px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        .message {
            margin-bottom: 10px;
            border-radius: 5px;
            padding: 5px;
            line-height: 1.5;
            display: flex;
            flex-direction: column;
            animation: fadeIn 0.5s ease-in-out; /* 应用淡入动画 */
        }

        .message.user {
            align-items: flex-end;
        }

        .message.ai {
            align-items: flex-start;
        }

        .bubble {
            background-color: #d9edf7;
            border-radius: 10px;
            padding: 10px;
            position: relative;
            max-width: 70%;
            display: inline-block;
        }

        .message-header {
            display: flex; /* 使用flex布局 */
            align-items: center; /* 垂直居中对齐 */
            gap: 10px; /* 设置元素之间的间隙 */
        }

        .name.ai {
            margin: 0;
        }

        .feedback-icons {
            display: flex;
            gap: 5px;
        }

        .feedback-icon {
            cursor: pointer;
        }

        .feedback-icon.useful {
            color: green;
        }

        .feedback-icon.not-useful {
            color: red;
        }

        .feedback-input {
            display: none; /* 默认隐藏反馈输入框 */
            margin-top: 5px;
        }

        .selected {
            color: #4CAF50; /* 选中状态的颜色 */
        }

        .disabled {
            color: #ccc; /* 禁用状态的颜色 */
            pointer-events: none; /* 禁用点击事件 */
        }

        .time.ai {
            margin-left: auto; /* 将时间推到其容器的最右边 */
        }

        .bubble.ai {
            background-color: #d9edf7;
            border-radius: 10px;
            padding: 10px;
            position: relative;
            max-width: 70%;
            display: inline-block;
        }


        .params.ai {
            display: flex; /* 使用flex布局显示params */
            flex-wrap: wrap; /* 允许params换行 */
            gap: 5px; /* 设置params之间的间隙 */
            margin-top: 10px; /* 在params和消息气泡之间添加一点间隙 */
        }

        .param-tag {
            background-color: #e1f5fe; /* 设置背景颜色 */
            border-radius: 3px; /* 圆角边框 */
            padding: 3px 6px; /* 内边距 */
            font-size: 0.8em; /* 字体大小 */
            color: #0277bd; /* 字体颜色 */
            white-space: nowrap; /* 防止文本换行 */
        }

        #message {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin: 0 20px;
            flex-grow: 1;
        }

        #send {
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 0 20px;
        }

        #send:hover {
            background-color: #45a049;
        }

        #input-area {
            display: flex;
            margin-bottom: 20px;
        }

        table {
            border-collapse: collapse;
            width: 60%;
        }

        th, td {
            border: 1px solid black;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
            font-weight: bold;
        }
    </style>
</head>
<body>
<div id="chatbox">
    <!-- Chat messages will be added here -->
</div>
<div id="input-area">
    <input id="message" type="text" placeholder="Type your message here...">
    <button id="send">Send</button>
</div>

<script>
    var sessionId = Date.now() + Math.random().toString(36).substr(2, 9);
    sessionStorage.setItem('sessionId', sessionId);

    document.getElementById("send").addEventListener("click", function () {
        sendMessage();
    });

    document.getElementById("message").addEventListener("keydown", function (e) {
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    function sendMessage() {
        var msg = document.getElementById("message").value;
        // User's message
        var msgDiv = document.createElement("div");
        var nameDiv = document.createElement("div");
        var bubbleDiv = document.createElement("div");
        msgDiv.className = "message user";
        nameDiv.textContent = "YOU";
        nameDiv.className = "name user";
        bubbleDiv.textContent = msg;
        bubbleDiv.className = "bubble user";

        msgDiv.appendChild(nameDiv);
        msgDiv.appendChild(bubbleDiv);
        document.getElementById("chatbox").appendChild(msgDiv);
        scrollToBottom();

        let apiUrl = window.location.origin + '/api/chat/v1/dialogue';
        fetch(apiUrl, {
            method: 'POST',
            headers: {
                'Accept': 'text/event-stream',
                'Content-Type': 'application/json',
                'appId': '10000',
                'timestamp': '1709538875',
                'token': '0dd9697a6b8e2d6d7d0634da9c0696c6'
            },
            body: JSON.stringify({
                conversationId: sessionStorage.getItem("sessionId"),
                version: "1.0.0",
                input: msg
            })
        })
            .then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('Network response was not ok');
                }
            })
            .then(data => {
                // AI's response
                var jsonData = JSON.parse(data.replace("data:", ""));
                var msgDiv = document.createElement("div");
                var headerDiv = document.createElement("div");
                var nameDiv = document.createElement("div");
                var timeDiv = document.createElement("div");
                var bubbleDiv = document.createElement("div");
                var paramsDiv = document.createElement("div");
                msgDiv.className = "message ai";

                headerDiv.className = "message-header"; // 为头部信息div设置一个class
                nameDiv.textContent = "AI";

                nameDiv.className = "name ai";
                headerDiv.appendChild(nameDiv); // 将AI标签添加到头部信息div

                var feedbackInput = document.createElement("input");
                feedbackInput.type = "text";
                feedbackInput.id = "feedback-text-" + jsonData.id;
                feedbackInput.placeholder = "Please provide feedback...";
                feedbackInput.className = "feedback-input";
                feedbackInput.onchange = function () {
                    sendFeedbackWithText(jsonData.id);
                };

                var feedbackIconsDiv = document.createElement("div");
                feedbackIconsDiv.className = "feedback-icons";

                var usefulIcon = document.createElement("i");
                usefulIcon.id = "useful-" + jsonData.id;
                usefulIcon.className = "material-icons feedback-icon";
                // usefulIcon.textContent = "thumb_up";
                usefulIcon.addEventListener("click", function () {
                    handleUsefulClick(jsonData.id);
                });

                var notUsefulIcon = document.createElement("i");
                notUsefulIcon.id = "not-useful-" + jsonData.id;
                notUsefulIcon.className = "material-icons feedback-icon";
                // notUsefulIcon.textContent = "thumb_down";
                notUsefulIcon.addEventListener("click", function () {
                    handleNotUsefulClick(jsonData.id);
                });

                feedbackIconsDiv.appendChild(usefulIcon);
                feedbackIconsDiv.appendChild(notUsefulIcon);

                headerDiv.appendChild(feedbackIconsDiv);
                headerDiv.appendChild(feedbackInput);

                var date = new Date(jsonData.createTime);
                timeDiv.textContent = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
                timeDiv.className = "time ai";
                headerDiv.appendChild(timeDiv); // 将时间添加到头部信息div

                bubbleDiv.innerHTML = marked.parse(jsonData.content); // 使用 marked 解析 Markdown 内容
                bubbleDiv.className = "bubble ai";

                var chartsDiv = document.createElement("div");
                chartsDiv.id = "charts_" + jsonData.id;
                chartsDiv.style.width = "850px";
                chartsDiv.style.height = "400px";

                if (jsonData.params && jsonData.params.length > 0) {
                    jsonData.params.forEach(function (param) {
                        var paramSpan = document.createElement("span");
                        paramSpan.textContent = param;
                        paramSpan.className = "param-tag"; // 应用新的param-tag样式类
                        paramsDiv.appendChild(paramSpan); // 将每个param标签添加到params div中
                    });
                    paramsDiv.className = "params ai"; // 给params的div添加一个class
                }
                var contentType = jsonData.contentType;
                if ('CHART' === contentType && isJSON(jsonData.content)) {
                    var parse = JSON.parse(jsonData.content);
                    msgDiv.appendChild(headerDiv);
                    msgDiv.appendChild(chartsDiv);
                    msgDiv.appendChild(paramsDiv);
                    document.getElementById("chatbox").appendChild(msgDiv); // 先将 msgDiv 添加到 chatbox
                    scrollToBottom();
                    setBarChart(parse, jsonData.id); // 然后调用 setBarChart 函数
                    return;
                }
                if ('EXCEL' === contentType) {
                    var excelTable = document.createElement("table");
                    excelTable.id = "excel_" + jsonData.id;
                    // thead
                    var excelThead = document.createElement("thead");
                    excelTable.appendChild(excelThead);
                    // tbody
                    var excelTbody = document.createElement("tbody");
                    excelTable.appendChild(excelTbody);
                    var parse = JSON.parse(jsonData.content);
                    msgDiv.appendChild(headerDiv);
                    msgDiv.appendChild(excelTable);
                    msgDiv.appendChild(paramsDiv);
                    document.getElementById("chatbox").appendChild(msgDiv); // 先将 msgDiv 添加到 chatbox
                    scrollToBottom();
                    setExcelTable(parse, jsonData.id);
                    return;
                }
                // 将头部信息div和消息内容div添加到消息div
                msgDiv.appendChild(headerDiv);
                msgDiv.appendChild(bubbleDiv);
                msgDiv.appendChild(paramsDiv);

                document.getElementById("chatbox").appendChild(msgDiv);
                scrollToBottom();
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
            });

        document.getElementById("message").value = "";
    }

    function scrollToBottom() {
        chatbox.scrollTop = chatbox.scrollHeight;
    }

    function setExcelTable(tableChart, id) {
        var data = tableChart.data;
        var table = document.getElementById("excel_" + id);

        // 创建一个包裹 div，并应用气泡样式
        var bubbleDiv = document.createElement("div");
        bubbleDiv.className = "bubble ai";
        bubbleDiv.style.width = "100%"; // 确保表格占满气泡

        const tableContent = document.createElement("caption");
        tableContent.textContent = tableChart.content;
        tableContent.style.textAlign = "left"; // 使说明内容居左
        tableContent.style.fontSize = "12px";
        bubbleDiv.appendChild(tableContent); // 将说明内容添加到气泡内

        table.parentNode.insertBefore(bubbleDiv, table); // 将气泡插入到表格之前
        bubbleDiv.appendChild(table); // 将表格添加到气泡内

        // 创建表格标题
        const tableCaption = document.createElement("caption");
        tableCaption.textContent = tableChart.title;
        table.appendChild(tableCaption);
        const thead = table.getElementsByTagName("thead")[0];
        const tbody = table.getElementsByTagName("tbody")[0];
        // 创建表头
        if (data.length > 0) {
            const headerRow = document.createElement("tr");
            Object.keys(data[0]).forEach((key) => {
                const headerCell = document.createElement("th");
                headerCell.textContent = key;
                headerRow.appendChild(headerCell);
            });
            thead.appendChild(headerRow);
        }
        // 创建表格内容
        data.forEach((item) => {
            const row = document.createElement("tr");
            Object.values(item).forEach((value) => {
                const cell = document.createElement("td");
                cell.textContent = value;
                row.appendChild(cell);
            });
            tbody.appendChild(row);
        });
    }

    function setBarChart(json, id) {
        var chartContainer = document.getElementById("charts_" + id);

        // 创建一个包裹 div，并应用气泡样式
        var bubbleDiv = document.createElement("div");
        bubbleDiv.className = "bubble ai";
        bubbleDiv.style.width = "100%"; // 确保图表占满气泡

        var textDescription = document.createElement("div");
        textDescription.style.fontSize = "16px";
        textDescription.innerHTML = marked.parse(json.answer);
        bubbleDiv.appendChild(textDescription); // 将文本描述添加到气泡内

        chartContainer.parentNode.insertBefore(bubbleDiv, chartContainer); // 将气泡插入到图表容器之前
        bubbleDiv.appendChild(chartContainer); // 将图表容器添加到气泡内

        var myChart = echarts.init(chartContainer);
        var option;
        var series = [];
        var dataList = json.data;
        if (dataList) {
            for (var i = 0; i < dataList.length; i++) {
                var dataItem = {
                    name: dataList[i].name,
                    type: dataList[i].type,
                    data: dataList[i].value,
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                };
                if (dataList[i].yAxisIndex) {
                    dataItem.yAxisIndex = dataList[i].yAxisIndex - 1;
                }
                series.push(dataItem);
            }
        }
        var yAxisList = [];
        var yAxisData = json.yAxis;
        if (yAxisData) {
            for (var j = 0; j < yAxisData.length; j++) {
                var yAxisItem = {
                    type: 'value',
                    name: yAxisData[j].name,
                    alignTicks: true,
                    axisLabel: {
                        formatter: '{value} ' + yAxisData[j].formatter
                    }
                };
                if (j > 1) {
                    yAxisItem.position = 'right';
                }
                if (j > 2) {
                    yAxisItem.offset = 80;
                }
                yAxisList.push(yAxisItem);
            }
        } else {
            var yAsixDefault = {
                type: 'value'
            };
            yAxisList.push(yAsixDefault);
        }
        option = {
            title: {
                text: json.title,
                show: true,
                left: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: json.xAxis.data
            },
            yAxis: yAxisList,
            series: series
        };
        myChart.setOption(option, true);
    }

    function isJSON(str) {
        try {
            JSON.parse(str);
        } catch {
            return false;
        }
        return true;
    }

    function handleUsefulClick(id) {
        // Mark as useful and send feedback immediately
        sendFeedback(id, 1, '');
        document.getElementById('useful-' + id).classList.add('selected');
        document.getElementById('not-useful-' + id).classList.add('disabled');
    }

    function handleNotUsefulClick(id) {
        // Show feedback input when not useful is clicked
        var feedbackInput = document.getElementById('feedback-text-' + id);
        feedbackInput.style.display = 'block';
        feedbackInput.focus();

        document.getElementById('useful-' + id).classList.add('disabled');
        document.getElementById('not-useful-' + id).classList.add('selected');
    }

    function sendFeedbackWithText(id) {
        var feedbackText = document.getElementById('feedback-text-' + id).value;
        sendFeedback(id, 2, feedbackText);
        document.getElementById('feedback-text-' + id).style.display = 'none';
    }

    function sendFeedback(id, usefulness, feedback) {
        fetch(window.location + 'api/chat/record/feedback', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'appId': '10000',
                'timestamp': '1709538875',
                'token': '0dd9697a6b8e2d6d7d0634da9c0696c6'
            },
            body: JSON.stringify({
                id: id,
                usefulness: usefulness,
                feedback: feedback
            })
        })
            .then(response => response.json())
            .then(data => {
                console.log('Feedback sent:', data);
                // Update the UI based on the feedback
            })
            .catch(error => {
                console.error('Error sending feedback:', error);
            });
    }
</script>
</body>
</html>